package com.abc.base.common.exceptions;


import com.abc.base.common.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(BindException.class)
    public Result<String> handleValidationExceptions(BindException ex, HttpServletResponse response) {
        String errorMessage = "参数验证失败";
        Map<String, String> errors = new HashMap<>();
        for (ObjectError error : ex.getBindingResult().getAllErrors()) {
            String fieldName = ((FieldError) error).getField();
            errorMessage += error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        }
        log.error("参数验证失败，错误信息：{}", errors);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return Result.error(errorMessage);
    }

    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return Result.error("系统异常，请联系管理员,错误原因是：" + e.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public Result<String> handleIllegalArgumentException(IllegalArgumentException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return Result.error("参数错误,错误原因是：" + e.getMessage());
    }

    @ExceptionHandler(AuthorizationException.class)
    public Result<String> handleAuthorizationException(AuthorizationException e, HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return Result.error("权限不足,错误原因是：" + e.getMessage());
    }
}
